package me.zhengjie.config;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author 雨来
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        final RestTemplate restTemplate = new RestTemplate();
        final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        final HttpClient httpClient = HttpClientBuilder.create()
                .setConnectionManager(getPoolingHttpClientConnectionManager())
                .setRedirectStrategy(new LaxRedirectStrategy()).build();
        //获取链接超时时间
        factory.setConnectionRequestTimeout(3000);
        // 指客户端和服务器建立连接的timeout
        factory.setConnectTimeout(3000);
        // socketTimeout 读取数据的超时时间
        factory.setReadTimeout(120000);
        factory.setHttpClient(httpClient);
        restTemplate.setRequestFactory(factory);
        return restTemplate;
    }

    public PoolingHttpClientConnectionManager getPoolingHttpClientConnectionManager() {
        PoolingHttpClientConnectionManager connectionPoolManager = new PoolingHttpClientConnectionManager();
        //最大连接数
        connectionPoolManager.setMaxTotal(100);
        //每个路由默认接收的最大连接数
        connectionPoolManager.setDefaultMaxPerRoute(200);
        return connectionPoolManager;
    }
}